import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

export const useUserStore = defineStore('user', () => {
    const token = ref(localStorage.getItem('token') || '')
    const user = ref(JSON.parse(localStorage.getItem('user') || '{}'))
    const isLoggedIn = computed(() => !!token.value)
    const isAdmin = computed(() => {
        return user.value?.roles?.includes('admin') || false
    })

    // 设置认证信息
    function setAuth(authData: { token: string; user: any }) {
        token.value = authData.token
        user.value = authData.user
        localStorage.setItem('token', authData.token)
        localStorage.setItem('user', JSON.stringify(authData.user))
        // 设置axios默认请求头
        axios.defaults.headers.common['Authorization'] = `Bearer ${authData.token}`
    }

    // 清除认证信息
    function clearAuth() {
        token.value = ''
        user.value = {}
        localStorage.removeItem('token')
        localStorage.removeItem('user')
        delete axios.defaults.headers.common['Authorization']
    }

    // 登录
    async function login(loginData: any) {
        try {
            console.log('正在发送登录请求...')

            // 尝试不同的API路径
            const apiPaths = [
                'http://localhost:3000/api/auth/login',
                'http://localhost:3000/auth/login',
                'http://localhost:3000/api/v1/auth/login',
                'http://localhost:3000/api/auth/signin',
                'http://localhost:3000/api/users/login',
                'http://localhost:3000/api/users/signin',
                'http://localhost:3000/api/v1/auth/signin',
                'http://localhost:3000/api/v1/users/login',
                'http://localhost:3000/api/v1/users/signin',
                'http://localhost:3000/api/user/login',
                'http://localhost:3000/api/user/signin',
                'http://localhost:3000/auth/signin'
            ]

            let response = null
            let successPath = ''
            let lastError = null

            // 依次尝试不同的路径
            for (const apiPath of apiPaths) {
                try {
                    console.log(`尝试路径: ${apiPath}`)
                    response = await axios({
                        method: 'post',
                        url: apiPath,
                        data: loginData,
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        timeout: 5000
                    })

                    successPath = apiPath
                    console.log(`成功使用路径: ${apiPath}`)
                    break
                } catch (e) {
                    console.log(`路径 ${apiPath} 请求失败:`, e.message)
                    lastError = e
                }
            }

            // 如果所有路径都失败了
            if (!response) {
                throw lastError || new Error('所有API路径请求都失败')
            }

            console.log(`登录成功，使用路径: ${successPath}`)
            console.log('登录响应:', response)

            // 检查响应格式，适配不同的API返回格式
            const responseData = response.data
            let authData

            if (responseData.success && responseData.data) {
                // 标准格式：{ success: true, data: { token, user } }
                authData = {
                    token: responseData.data.token,
                    user: responseData.data.user
                }
            } else {
                // 简单格式：{ token, user }
                authData = {
                    token: responseData.token,
                    user: responseData.user
                }
            }

            setAuth(authData)
            ElMessage.success('登录成功')
            return authData
        } catch (error: any) {
            let errorMsg = '登录失败'

            if (error.message === 'Network Error') {
                errorMsg = '网络错误，请确保后端服务器已启动'
            } else if (error.response && error.response.data) {
                if (typeof error.response.data === 'string') {
                    errorMsg = error.response.data
                } else if (error.response.data.message) {
                    errorMsg = error.response.data.message
                }
            }

            ElMessage.error(errorMsg)
            throw error
        }
    }

    // 注册
    async function register(registerData: any) {
        try {
            console.log('正在发送注册请求...')

            // 尝试不同的API路径
            const apiPaths = [
                'http://localhost:3000/api/auth/register',
                'http://localhost:3000/api/users/register',
                'http://localhost:3000/api/v1/users/register'
            ]

            let response = null
            let successPath = ''
            let lastError = null

            // 依次尝试不同的路径
            for (const apiPath of apiPaths) {
                try {
                    console.log(`尝试路径: ${apiPath}`)
                    response = await axios({
                        method: 'post',
                        url: apiPath,
                        data: registerData,
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        timeout: 5000
                    })

                    successPath = apiPath
                    console.log(`成功使用路径: ${apiPath}`)
                    break
                } catch (e) {
                    console.log(`路径 ${apiPath} 请求失败:`, e.message)
                    lastError = e
                }
            }

            // 如果所有路径都失败了
            if (!response) {
                throw lastError || new Error('所有API路径请求都失败')
            }

            console.log(`注册成功，使用路径: ${successPath}`)
            console.log('注册响应:', response)

            // 检查响应是否成功
            if (response.data.success || response.status === 201) {
                ElMessage.success('注册成功')
                return response.data
            } else {
                throw new Error(response.data.message || '注册失败')
            }
        } catch (error: any) {
            console.error('注册请求错误:', error)

            // 提取错误信息
            let errorMsg = '注册失败'
            if (error.response) {
                console.log('错误状态码:', error.response.status)
                console.log('错误数据:', error.response.data)

                if (error.response.data) {
                    if (typeof error.response.data === 'string') {
                        errorMsg = error.response.data
                    } else if (error.response.data.message) {
                        errorMsg = error.response.data.message
                    } else if (error.response.data.error) {
                        errorMsg = error.response.data.error
                    }
                }
            } else if (error.message) {
                errorMsg = error.message
            }

            ElMessage.error(errorMsg)
            throw error
        }
    }

    // 登出
    function logout() {
        // 可以在这里添加调用登出API的逻辑
        // try {
        //   await axios.post('/api/auth/logout')
        // } catch (error) {
        //   console.error('登出请求失败:', error)
        // }

        clearAuth()
        ElMessage.success('已退出登录')
    }

    // 获取用户信息
    async function fetchUserInfo() {
        if (!token.value) return null

        try {
            // 首先尝试使用API获取
            let userData = null
            let apiError = null

            try {
                const response = await axios.get('/api/users/profile')

                // 检查响应格式，适配不同的API返回格式
                if (response.data.success && response.data.data) {
                    // 标准格式：{ success: true, data: { ... } }
                    userData = response.data.data
                } else if (response.data.status && response.data.data) {
                    // 状态格式：{ status: 200, data: { ... } }
                    userData = response.data.data
                } else {
                    // 简单格式：{ ... }
                    userData = response.data
                }
            } catch (error) {
                apiError = error
                console.warn('API获取用户信息失败，使用本地缓存', error)
            }

            // 如果API失败，使用本地缓存或默认用户
            if (!userData) {
                userData = user.value

                // 如果没有现有的用户数据，设置一个临时用户
                if (!userData || Object.keys(userData).length === 0) {
                    userData = {
                        id: 'temp-user',
                        username: 'temp-user',
                        email: 'temp@example.com',
                        roles: ['user'],
                        isTemporary: true // 标记为临时用户
                    }
                }
            }

            user.value = userData
            localStorage.setItem('user', JSON.stringify(userData))
            return userData
        } catch (error: any) {
            console.error('获取用户信息失败:', error)

            // 创建一个临时用户防止UI错误
            if (error.response?.status === 401 || !user.value || Object.keys(user.value).length === 0) {
                const tempUser = {
                    id: 'temp-user',
                    username: 'temp-user',
                    email: 'temp@example.com',
                    roles: ['user'],
                    isTemporary: true
                }
                user.value = tempUser
                localStorage.setItem('user', JSON.stringify(tempUser))
                return tempUser
            }

            return user.value
        }
    }

    // 更新用户信息
    async function updateUserInfo(userData: any) {
        try {
            const response = await axios.patch('/api/users/profile', userData)

            // 检查响应格式，适配不同的API返回格式
            let updatedUserData

            if (response.data.success && response.data.data) {
                // 标准格式：{ success: true, data: { ... } }
                updatedUserData = response.data.data
            } else if (response.data.status && response.data.data) {
                // 状态格式：{ status: 200, data: { ... } }
                updatedUserData = response.data.data
            } else {
                // 简单格式：{ ... }
                updatedUserData = response.data
            }

            user.value = updatedUserData
            localStorage.setItem('user', JSON.stringify(updatedUserData))
            ElMessage.success('个人信息更新成功')
            return updatedUserData
        } catch (error: any) {
            const errorMsg = error.response?.data?.message || '更新失败'
            ElMessage.error(errorMsg)
            throw error
        }
    }

    // 修改密码
    async function changePassword(passwordData: any) {
        try {
            await axios.post('/api/users/change-password', passwordData)
            ElMessage.success('密码修改成功')
        } catch (error: any) {
            ElMessage.error(error.response?.data?.message || '密码修改失败')
            throw error
        }
    }

    // 删除账号
    async function deleteAccount(password: string) {
        try {
            await axios.post('/api/users/delete-account', { password })
            clearAuth()
            ElMessage.success('账号已注销')
            return true
        } catch (error: any) {
            ElMessage.error(error.response?.data?.message || '账号注销失败')
            throw error
        }
    }

    return {
        token,
        user,
        isLoggedIn,
        isAdmin,
        login,
        register,
        logout,
        fetchUserInfo,
        updateUserInfo,
        changePassword,
        deleteAccount,
        setAuth,
        clearAuth
    }
}) 